"use strict";

const Service = require("egg").Service;

class BannersService extends Service {
  async index({ page, pageSize } = { page: 1, pageSize: 10 }) {
    const { ctx } = this;
    // Fetch all banners from the database
    const result = await ctx.model.Banner.findAndCountAll({
      order: [
        ["sort", "DESC"],
        ["createdAt", "DESC"],
      ], // Sort by sort field and createdAt
      offset: (page - 1) * pageSize,
      limit: pageSize,
    });
    return {
      rows: result.rows,
      count: result.count,
    };
  }

  async create(bannerData) {
    const { ctx } = this;
    // Create a new banner
    const newBanner = await ctx.model.Banner.create(bannerData);
    return newBanner;
  }

  async destroy(id) {
    const { ctx } = this;
    // Delete a banner by ID
    const result = await ctx.model.Banner.destroy({
      where: { id },
    });
    return result > 0; // 返回是否删除成功
  }

  async batchDelete(ids) {
    const { ctx } = this;
    // Delete multiple banners by IDs
    const result = await ctx.model.Banner.destroy({
      where: { id: ids },
    });
    return result > 0; // 返回是否删除成功
  }

  async update(id, bannerData) {
    const { ctx } = this;
    // Update a banner by ID
    const [updatedRows] = await ctx.model.Banner.update(bannerData, {
      where: { id },
    });
    return updatedRows > 0; // 返回是否更新成功
  }
}

module.exports = BannersService;
